<?php
defined('SYSPATH') or die('No direct script access.');
class Controller_Ajax extends Controller {
    private $result;

    public function before()
    {
        parent::before();
        if( ! $this->request->is_ajax() ) {
            throw new Kohana_Exception('Request is not AJAX');
        }
    }

    public function after()
    {
        $this->response->headers(array(
            'Content-Type'  => 'text/json',
            'Pragma'        => 'no-cache',
            'Cache-Control' => 'no-store, no-cache, must-revalidate',
        ));
        $this->response->body($this->result);
        parent::after();
    }

    public function action_getpage()
    {
        $result=array();
        $page=$this->request->post('page');
        $quantity=$this->request->post('grid_length');
        $start=($page-1)*$quantity;
        $result['pages']=ceil((ORM::factory('image')->find_all()->count())/$quantity);
        $result['tmp']=ORM::factory('image')->limit($quantity)->offset($start)->order_by('id','DESC')->find_all();
        foreach ($result['tmp'] as $obj)
        {
            $result['data'][]=$obj->as_array();
        }
        $this->result=json_encode($result);
    }

    public function action_getimageinfo()
    {
        $result=array();
        $id=$this->request->post('id');
        $result=ORM::factory('image',$id)->as_array();
        $this->result=json_encode($result);
    }
}